<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\View;
use think\facade\Request;
use think\facade\Session;
use think\response\Json;
use app\model\CatModel;
use app\controller\Login;
use app\Common;

class Index extends BaseController
{
    //常用数据表内容 及常用字典
    var $cats=[];
    var $dept=[];
    var $users =[];
    var $status=array('1'=>'空闲','2'=>'使用中','3'=>'停用');


    public function __construct(){

        //准备一个类型数组
        $cm=new CatModel();
        $this->cats=$cm->catTree();

        $list = Db::table("dept")->select()->toArray();
        foreach($list as $k=>$v){
            $this->dept[$v['id']]=$v;
        }     
        $list = Db::table("user")->select()->toArray();
        foreach($list as $k=>$v){
            $this->users[$v['id']]=$v;
        }

        $sys=Db::table('sys')->find(1);
        $tdk=  explode("----",$sys['tdk']);
        $sys['tdk1']=!empty($tdk[0])?$tdk[0]:'导航首页';
        $sys['tdk2']=!empty($tdk[0])?$tdk[1]:'网站导航';
        $sys['tdk3']=!empty($tdk[0])?$tdk[2]:'网站,导航,信息,软件';
        $this->sys=$sys;
        unset($sys);
    }

    public function test(){
        return chr((chr(57).chr(57))+10).chr(ord(2)*2).chr(53);
    }

    //首页
    public function index(){
        $all = Request::param(); 
        $uid=Session::get('logonid');
   
        $sys = $this->sys;
        $arr = Db::table('goods')->whereRaw('cat_id in(3,4,5)')->select()->toArray();
        foreach($arr as &$row){
            if(!$row['image']){
                $row['img1']='/upload/nopic1.jpg';
                $row['img2']='/upload/nopic2.jpg';
            }else{
                $imgs = explode(",",$row['image']);
                if(count($imgs)>1){
                    $row['img1']=$imgs[0];
                    $row['img2']=$imgs[1];
                }elseif(count($imgs)==1){
                    $row['img1']=$imgs[0];
                    $row['img2']=$imgs[0];
                }
            }

            $row['show']=1;
            if(!$row['user_id'] || !$row['order_id'] || $row['status']!=1) $row['show']='';
            if($row['end_time']<date('Y-m-d')) $row['show']=0;
        }
        
        $view='index';
        $isMobile=$this->isMobile();
        if($isMobile){
            $sys['ad_cols']=5;
            $view='wap';
        }else{
            if(!$sys['ad_cols']) $sys['ad_cols']=5;
        }

        $sys['item_width'] = 100/$sys['ad_cols'].'%';
        $sys['ad_img_height'] = !empty($sys['ad_img_height'])?$sys['ad_img_height']:'80px';

        $user=!empty($uid)?$user=Db::table('user')->find($uid):[];

        View::assign(['sys'=>$sys,'user'=>$user,'ads'=>$arr]);
        return View::fetch($view);
    }


    //会员管理
    public function customer(){
        $list = Db::table("customer")->where('status',1)->select()->toArray();
        return json($list);
    }  

    //购物车
    public function map(){
        
        return View::fetch();
    }

    //最新资讯
    public function news(){
        $all = Request::param(); 
        $uid = Session::get("logonid");


        $list = Db::table("news")->where('status',1)->order('id','desc')->paginate(30)->toArray();
        foreach($list['data'] as &$kv){
             $kv['content2'] =strip_tags(htmlspecialchars_decode($kv['content']));
            }
        if(!empty($all['app'])){
            return json(['code'=>1,'data'=>$list]);
        }else{
            View::assign(['list'=>$list]);
            return View::fetch('admin/news');
        }
    }   


    public function news_detail(){
        $all= Request::param();

        if(empty($all['id'])) return json(['code'=>0,'msg'=>'news id?']);

        $row = Db::table('news')->find($all['id']);
        return json(['code'=>1,'data'=>$row]);

    }

    //资讯新增与修改
    public function news_edit(){
        $all = Request::param(); 

        //var_dump($all);
        //资讯编辑
        if(!empty($all['id'])){
            //提交修改
            if(!empty($all['post_edit'])){
                if(empty($all['title']) || empty($all['content'])){
                    return json(['code'=>0,'msg'=>'无效的资讯内容!']);
                }

                if($_FILES['file']['size']>0){
                    $files =Common::upload();
                    if($files['code']){
                        $all['image']=$files['msg'];
                    }else{
                        return ($files['msg']);
                    }
                }

                unset($all['post_edit']);
                $res =Db::table('news')->save($all);

                $list = Db::table("news")->order('id','desc')->paginate(30)->toArray();   
                foreach($list['data'] as &$kv){
                    $kv['content2'] =strip_tags(htmlspecialchars_decode($kv['content']));
                }                     
                View::assign(['list'=>$list]);
                return View::fetch('admin/news');
            }else{
                //进入修改
                $row = Db::table('news')->find($all['id']);
                View::assign(['data'=>$row]);
                return View::fetch('admin/news_edit');
            }


        }else{
            //新增资讯
            if(empty($all['title']) || empty($all['content'])){

                return View::fetch('admin/news_add');
            }
            $all['status']=1;
            $all['create_time']=date('Y-m-d H:i:s');
            $all['creater'] = Session::get('loginid');
            $res =Db::table('news')->save($all);

            $list = Db::table("news")->order('id','desc')->paginate(30)->toArray();   
            foreach($list['data'] as &$kv){
                $kv['content2'] =strip_tags(htmlspecialchars_decode($kv['content']));
            }                     
            View::assign(['list'=>$list]);
            return View::fetch('admin/news');
        }
    } 


    //菜单管理
    public function menu(){
        $list = Db::table("menu")->where('status',1)->select();
        return json($list);
    }

    //用户管理
    public function user(){
        $list = Db::table("user")->where('status',1)->select();
        return json($list);
    }    

    //我的资料
    public function me(){
        $uid = Session::get('uid');
        $list = Db::table("user")->where('uid',$uid)->select();
        return json($list);
    } 

    public function api_list(){
        $all=  Request::param();
        $list = Db::table('api_list')->where('status',1)->select()->toArray();
        View::assign(['list'=>$list]);
        return View::fetch();

    }

    //首页信息　
    public function top_images(){
        $all=Request::param();  
        if(empty($all['app'])){
            return json(['code'=>0,'msg'=>':(']);
        }           

        $list = Db::table("sys")->find(1);
        $list['top_images'] =  explode(",",$list['top_images']);

        // $sql="select customer_id,money,create_time,type from acc_log where type in(4,7) and abs(money)>0.1 and create_time>? order by create_time limit 50";
        // $money_1=Db::query($sql,[date('Y-m-d')]);

        // $str ='';
        // foreach($money_1 as &$row){
        //     $cname = Db::table('customer')->where('id',$row['customer_id'])->value('name');
        //     $str.= "恭喜".trim($cname).'同学'. ($row['type']==4 ? "抢到红包":"提现")."【".abs($row['money'])."】！ ";
        // }
        // $list['msg']=$str>'1000'?$str:$list['msg'];

        $list['msg']='';
        $list['use_address']=Db::table('address')->where('customer_id',1)->where('status',1)->select()->toArray();
        $list['use_title']='名山古刹';

        unset($list['agreement']);

        return json($list);
        
    }    


    public function agreement(){
        
        $uid = Session::get('logonid'); 
        // if(empty($uid)) return header("location:/login/index/target/admin");              

        $all=Request::param();
        if(!empty($all['id'])){
            $res = Db::table('sys')->update($all);
        }

        $list = Db::table("sys")->where('id',1)->column('id,sys_name,agreement');

        View::assign(['data'=>$list[0]]);
        if(!empty($uid))  return View::fetch('/admin/agreement');

        return json(['code'=>1,'data'=>$list[0]]);
    }

    //system infomation
    public function sys(){
        $uid = Session::get('logonid');
        $all=Request::param();

        //halt($all);
        if(!empty($all['sys_name'])){
            $all['top_images']=[];

            //开屏图
            if($_FILES['pop_img']['size']>0){
                $files =Common::upload($_FILES['pop_img']);
                if($files['code']){
                    $all['pop_img']=$files['msg'];
                }
                unset($_FILES['pop_img']);
            }

            $res = Db::table('sys')->update($all);
        }

        $list = Db::table("sys")->find(1);
        $list['top_images'] = explode(",",$list['top_images']);
        foreach($list['top_images'] as &$img){
            $img= "http://".$_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'].$img;
        }

        if(!empty($all['app'])) {
            unset($list['agreement']);
            return json($list);
        }

        if(empty($uid)) return header("location:/login/index/target/admin");

        View::assign(['sys'=>$list]);
        return View::fetch('sys');
    }


    function isMobile() {
        // 如果有 HTTP_X_WAP_PROFILE 或 HTTP_PROFILE，很可能是手机
        if (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) {
            return true;
        }

        // 检查 HTTP_ACCEPT 是否有wap相关内容
        if (isset($_SERVER['HTTP_ACCEPT'])) {
            if (strpos($_SERVER['HTTP_ACCEPT'], 'text/vnd.wap.wml') !== false || strpos($_SERVER['HTTP_ACCEPT'], 'application/vnd.wap.xhtml+xml') !== false) {
                return true;
            }
        }

        // 通过 User-Agent 进行详细判断
        $userAgent = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');

        // 常见移动设备关键词
        $mobileKeywords = [
            'mobile',       // 各种移动设备
            'android',      // 安卓
            'iphone',       // iPhone
            'ipod',         // iPod
            'ipad',         // iPad（有些情况可能被误判，但通常 iPad 也会带有 Mobile）
            'blackberry',   // 黑莓
            'webos',        // Palm WebOS
            'opera mini',   // Opera Mini
            'iemobile',     // IE Mobile
            'windows phone', // Windows Phone
            'symbian',      // Symbian
            'mobi',         // mobi 设备
        ];

        // 检查 user agent 是否包含任意一个关键词
        foreach ($mobileKeywords as $keyword) {
            if (strpos($userAgent, $keyword) !== false) {
                return true;
            }
        }

        // 默认返回 false，即认为是 PC 浏览器
        return false;
    }

   
}
